package com.sendpo.zjx.sendpo.activity;

import android.app.Dialog;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.SystemClock;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.sendpo.zjx.sendpo.R;
import com.sendpo.zjx.sendpo.net.HttpCode;
import com.sendpo.zjx.sendpo.net.HttpUrl;
import com.sendpo.zjx.sendpo.utils.Tools;
import com.sendpo.zjx.sendpo.utils.Xutils;

import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.common.Callback;

import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.smssdk.EventHandler;
import cn.smssdk.SMSSDK;

/**
 * Created by Administrator on 2017/7/17.
 */

public class ForgetPassActivity extends AppCompatActivity {
    @BindView(R.id.head)
    RelativeLayout head;
    @BindView(R.id.user_iv)
    ImageView userIv;
    @BindView(R.id.getvalidate_bt)
    Button getvalidateBt;
    @BindView(R.id.edit_iphone)
    EditText editIphone;
    @BindView(R.id.accout_rl)
    RelativeLayout accoutRl;
    @BindView(R.id.inputpass_iv)
    ImageView inputpassIv;
    @BindView(R.id.edit_password)
    EditText editPassword;
    @BindView(R.id.inputpass_rl)
    RelativeLayout inputpassRl;
    @BindView(R.id.modifybt)
    RelativeLayout modifybt;
    @BindView(R.id.validate_iv)
    ImageView validateIv;
    @BindView(R.id.edit_yanzhen)
    EditText editYanzhen;
    @BindView(R.id.validate_rl)
    RelativeLayout validateRl;
    private String iphonetv = "";
    private YanzhenThread yanzhenThread;
    private EventHandler eventHandler;
    private boolean isZuce = false;
    public Dialog loadingdialog=null;
    public boolean isLoading=false;
    @BindView(value = R.id.edit_passwordconfirm)
    EditText edit_passwordconfirm;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Tools.initStatus(this, R.color.black);
        setContentView(R.layout.activity_forgetpass);
        ButterKnife.bind(this);
        initComponent();
    }

    public void initComponent() {
        yanzhenThread = new YanzhenThread(1000);
        loadingdialog=new Dialog(this);
        loadingdialog.setContentView(R.layout.dialog_loading);
        loadingdialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        loadingdialog.setCanceledOnTouchOutside(false);
        eventHandler = new EventHandler() {
            @Override
            public void afterEvent(int event, int result, final Object data) {
                super.afterEvent(event, result, data);
                switch (event) {
                    case SMSSDK.EVENT_GET_VERIFICATION_CODE:
                        if (result == SMSSDK.RESULT_COMPLETE) {
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    Toast.makeText(getApplicationContext(), "验证码已发送,请稍等..", Toast.LENGTH_SHORT).show();

                                }
                            });
                        } else {
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    String str = ((Throwable) data).getMessage();
                                    try {
                                        JSONObject jb = new JSONObject(str);
                                        Toast.makeText(getApplicationContext(), jb.getString("detail") + "", Toast.LENGTH_SHORT).show();
                                    } catch (JSONException e) {
                                        e.printStackTrace();
                                    }

                                }
                            });
                        }
                        break;

                    case SMSSDK.EVENT_SUBMIT_VERIFICATION_CODE:
                        if (result == SMSSDK.RESULT_COMPLETE) {
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    isZuce = true;
                                    forgetIphonePassword(editIphone.getText().toString().trim(),editPassword.getText().toString().trim());
                                }
                            });

                        } else {
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    String str = ((Throwable) data).getMessage();
                                    try {
                                        JSONObject jb = new JSONObject(str);
                                        Toast.makeText(getApplicationContext(), jb.getString("detail"), Toast.LENGTH_SHORT).show();
                                    } catch (JSONException e) {
                                        e.printStackTrace();
                                    }

                                }
                            });

                        }
                        break;
                }

            }
        };
        SMSSDK.registerEventHandler(eventHandler);
    }

    @OnClick(value = {R.id.getvalidate_bt, R.id.backbt, R.id.modifybt})
    public void onMyClick(View view) {
        switch (view.getId()) {
            case R.id.backbt:
                finish();
                break;
            case R.id.getvalidate_bt:
                if (TextUtils.isEmpty(editIphone.getText().toString().trim())) {
                    Toast.makeText(getApplicationContext(), "没有填写手机号码?", Toast.LENGTH_SHORT).show();
                    return;
                }
                yanzhenThread = new YanzhenThread(1000);
                yanzhenThread.start();
                this.iphonetv = editIphone.getText().toString().trim();
                SMSSDK.getVerificationCode("86", iphonetv);
                break;
            case R.id.modifybt:
                if (TextUtils.isEmpty(editIphone.getText().toString().trim())) {
                    Toast.makeText(getApplicationContext(), "手机号码不能为空", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (TextUtils.isEmpty(editPassword.getText().toString().trim())) {
                    Toast.makeText(getApplicationContext(), "修改密码不能为空", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (TextUtils.isEmpty(edit_passwordconfirm.getText().toString().trim())) {
                    Toast.makeText(getApplicationContext(), "确认密码不能为空", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (!TextUtils.equals(editPassword.getText().toString().trim(),edit_passwordconfirm.getText().toString().trim())) {
                    Toast.makeText(getApplicationContext(), "密码和确认密码不一致", Toast.LENGTH_SHORT).show();
                    return;
                }


                if (isZuce) {
                    forgetIphonePassword(editIphone.getText().toString().trim(),editPassword.getText().toString().trim());
                } else {
                    if (TextUtils.isEmpty(editYanzhen.getText().toString().trim())) {
                        Toast.makeText(getApplicationContext(), "验证码不能为空", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    SMSSDK.submitVerificationCode("86", iphonetv, editYanzhen.getText().toString().trim());
                }
                break;
        }
    }


    //忘记密码
    public void forgetIphonePassword(String userIphone,String userPassword){
        if(!isLoading){
            loadingdialog.show();
            isLoading=true;
            Map<String,String> map=new HashMap<>();
            map.put("userIphone",userIphone);
            map.put("userPassword",userPassword);
            Xutils.POST(HttpUrl.modifypasswordbyiphone, map, new Callback.CommonCallback<String>() {
                @Override
                public void onSuccess(String result) {
                    loadingdialog.dismiss();
                    isLoading=false;
                    String message="异常";
                    try {
                        JSONObject jb=new JSONObject(result);
                        message=jb.getString("message");
                        switch (jb.getInt("state")){
                            case HttpCode.SUCCESS:
                                setResult(RESULT_OK);
                                finish();

                                break;
                            case HttpCode.ERROR:
                                break;
                            case HttpCode.THROW:
                                break;
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    Toast.makeText(getApplicationContext(),message,Toast.LENGTH_SHORT).show();
                }

                @Override
                public void onError(Throwable ex, boolean isOnCallback) {
                    ex.printStackTrace();
                    loadingdialog.dismiss();
                    isLoading=false;
                    Toast.makeText(getApplicationContext(),"网络有误",Toast.LENGTH_SHORT).show();
                }

                @Override
                public void onCancelled(CancelledException cex) {

                }

                @Override
                public void onFinished() {

                }
            });



        }

    }

    private class YanzhenThread extends Thread {
        private boolean isLoading = true;
        private long sleep = 1000;
        private int time = 60;

        public YanzhenThread(long sleep) {
            this.sleep = sleep;
        }

        @Override
        public void run() {
            super.run();
            while (time != 0 && isLoading == true) {
                SystemClock.sleep(sleep);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (getvalidateBt != null) {
                            getvalidateBt.setClickable(false);
                            getvalidateBt.setTextColor(getResources().getColor(R.color.gray));
                            getvalidateBt.setText("重新发送还有" + time + "秒");
                        }

                    }
                });
                time--;
            }
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    if (getvalidateBt != null) {
                        getvalidateBt.setText("获取验证码");
                        getvalidateBt.setTextColor(getResources().getColor(R.color.default_theme));
                        getvalidateBt.setClickable(true);
                    }
                }
            });
            time = 60;
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (getvalidateBt != null) {
            yanzhenThread.isLoading = false;
            try {
                yanzhenThread.join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            yanzhenThread = null;
        }
        if (eventHandler != null) {
            SMSSDK.unregisterEventHandler(eventHandler);
        }
    }





}
